package cn.cy.creation.d03;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.lang.reflect.Constructor;

public class ReadXML1 {

    public static Object getInstanceByNameFromConfigFile() {
        try {
            // 创建文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            String configFilePath = "E:\\workspace-idea\\codeyoung\\java_project\\code_151_design_pattern\\src\\main\\resources\\config1.xml";
            doc = builder.parse(new File(configFilePath));
            // 获取包含类名的文本节点
            NodeList nl = doc.getElementsByTagName("className");
            Node classNode = nl.item(0).getFirstChild();
            String classPrefixName = "cn.codeyoung.creationPattern.d03.Client".concat("$");
            // 类全限定名
            String cName = classPrefixName.concat(classNode.getNodeValue());
            
            // 通过反射获取内部类实例
            Class<?> outerClass = Class.forName("cn.cy.creation.d03.Client");
            Client outerInstance = (Client) outerClass.newInstance();
            Class<?> c = Class.forName(cName);
            Constructor<?> innerConstructor = c.getDeclaredConstructor(outerClass);
            Object obj = innerConstructor.newInstance(outerInstance);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
}